package com.wxdc.nmgyt.nmgytwydc.app;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.location.LocationManager;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.squareup.leakcanary.LeakCanary;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.smtt.sdk.QbSdk;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.activity.MainActivity;
import com.wxdc.nmgyt.nmgytwydc.common.LocationService;
import com.wxdc.nmgyt.nmgytwydc.dagger.component.AppComponent;
import com.wxdc.nmgyt.nmgytwydc.dagger.component.DaggerAppComponent;
import com.wxdc.nmgyt.nmgytwydc.dagger.module.AppModule;
import com.wxdc.nmgyt.nmgytwydc.service.MyLocationService;
import com.wxdc.nmgyt.nmgytwydc.utils.GlideCacheUtil;
import com.wxdc.nmgyt.nmgytwydc.utils.SharedPreferenceUtil;

/**
 * Created by Administrator on 2018/3/16.
 */

public class MyApp extends Application {
    public LocationService locationService;//百度地图定位sdk，定位服务
    public LocationManager mLocationManager;
    public Vibrator mVibrator;
    private final String TAG = this.getClass().getSimpleName();
    private Object objLock = new Object();
    private static MyApp instance;
    private Intent mIntentService;
    private String htmlHttpAddress="";
    // 程序创建的时候执行
    @Override
    public void onCreate() {
        super.onCreate();
        /***
         * 初始化定位sdk，建议在Application中创建
         */
        locationService = new LocationService(getApplicationContext());
        mVibrator = (Vibrator) getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        SDKInitializer.initialize(getApplicationContext());
        synchronized (objLock) {
            if (mLocationManager == null) {
                mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }
        }
        instance = this;
        LeakCanary.install(this);//内存检测
        /*
        * 获取服务器IP地址
        * */
        if ("".equals(SharedPreferenceUtil.getHttp())) {
            String httpUrl = getResources().getString(R.string.http);
            SharedPreferenceUtil.setHttp(httpUrl);
        }
          /*绑定service*/
        mServiceConnection = new MyApp.MyServiceConnection();
        mIntentService = new Intent(this, MyLocationService.class);
        bindService(mIntentService, mServiceConnection, BIND_AUTO_CREATE);

        loadX5();
        htmlHttpAddress = SharedPreferenceUtil.getHttp().substring(0, SharedPreferenceUtil.getHttp().lastIndexOf(":"));
        //htmlHttpAddress = "http://192.168.0.104:9100";//SharedPreferenceUtil.getHttp();
        Log.i(TAG, "onCreate: ----------->"+htmlHttpAddress);
    }

    public static MyApp getInstance() {
        return instance;
    }

    public String getHTTPYd() {
        //return htmlHttpAddress+getResources().getString(R.string.js_yd);
        return "http://192.168.0.26"+getResources().getString(R.string.js_yd);
    }

    public String getHTTPCb() {
        //return  htmlHttpAddress+getResources().getString(R.string.js_cb);
        return  "http://192.168.0.26"+getResources().getString(R.string.js_cb);
    }

    public String getHTTPGm() {
        //return htmlHttpAddress+getResources().getString(R.string.js_gm);
        return "http://192.168.0.26"+getResources().getString(R.string.js_gm);
    }

    public String getHTTPPd() {
        //return htmlHttpAddress+getResources().getString(R.string.js_pd);
        return "http://192.168.0.26"+getResources().getString(R.string.js_pd);
    }
    public String getHTTPWz(){
        //return htmlHttpAddress+ getResources().getString(R.string.js_wz);
        return "http://192.168.0.26"+ getResources().getString(R.string.js_wz);
    }
    public String getHttpAddress(){
        return htmlHttpAddress;
    }
    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        Log.d(TAG, "onTerminate");
        locationService.stop();
        super.onTerminate();
    }

    @Override
    public void onLowMemory() {
        // 低内存的时候执行
        Log.d(TAG, "onLowMemory");
        super.onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        // 程序在内存清理的时候执行
        Log.d(TAG, "onTrimMemory");
        super.onTrimMemory(level);
    }
    /*
    将GPS设备采集的原始GPS坐标转换成百度坐标
    * */

    public LatLng latLngConVert(LatLng sourceLatLng) {
        CoordinateConverter converter = new CoordinateConverter();
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标
        converter.coord(sourceLatLng);
        LatLng desLatLng = converter.convert();
        return desLatLng;
    }

    /*
    * 检查定位权限
    * */
    public void checkLocaltionPermissions(Activity activity) {
        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.requestEach(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(new io.reactivex.functions.Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            Log.i(TAG, "accept: ----------" + permission.name + " is granted.");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Log.i(TAG, "accept: -------" + permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Log.i(TAG, "accept: -----------" + permission.name + " is denied.");
                        }
                    }
                });
    }

    /*
    * */
    public static AppComponent appComponent;
    public static AppComponent getAppComponent() {
        if (appComponent == null) {
            appComponent = DaggerAppComponent.builder()
                    .appModule(new AppModule(instance))
                    .build();
        }
        return appComponent;
    }

    /**/
    private  MyLocationService.MyBinder mBinder;
    private MyApp.MyServiceConnection mServiceConnection;
    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected: ----------");
            mBinder = (MyLocationService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected: ------------");
        }
    }
    public  MyLocationService.MyBinder getMyBinder(){
        return mBinder;
    }
    public void stopService(){
        unbindService(mServiceConnection);
        stopService(mIntentService);
    }

    private void loadX5(){
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);


            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);
    }
    /*
    * Toast提示信息
    * */
    public void showToastLongMessage(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }

    public void showToastShortMessage(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
}
